package com.sg.business.performence.model;

import java.util.ArrayList;
import java.util.List;

import org.bson.types.ObjectId;

import com.mobnut.db.DBActivator;
import com.mobnut.db.model.PrimaryObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.sg.business.model.IModelConstants;
import com.sg.business.model.Organization;
import com.sg.business.model.User;

public class AbstractEmployeeWorksDataSet {

	protected static List<String> getAllUserInOrganization(User user) {
		ArrayList<String> userIds = new ArrayList<String>();
		List<PrimaryObject> orgList = user.getWorksStatisticsSOrganization();
		List<ObjectId> subOrgIds = getSubOrganizationId(orgList);
		DBCollection userCol = getCollection(IModelConstants.C_USER);
		DBCursor cursor = userCol.find(new BasicDBObject().append(
				User.F_ORGANIZATION_ID,
				new BasicDBObject().append("$in", subOrgIds)),
				new BasicDBObject().append(User.F_USER_ID, 1));
		while (cursor.hasNext()) {
			String _userId = (String) cursor.next().get(User.F_USER_ID);
			userIds.add(_userId);
		}
		cursor.close();
		return userIds;
	}

	protected static DBCollection getCollection(String collectionName) {
		return DBActivator.getCollection(IModelConstants.DB, collectionName);
	}

	protected static List<ObjectId> getSubOrganizationId(
			List<PrimaryObject> orgList) {
		List<ObjectId> result = new ArrayList<ObjectId>();
		for (PrimaryObject po : orgList) {
			Organization organization = (Organization) po;
			result.add(organization.get_id());
			List<PrimaryObject> children = organization
					.getChildrenOrganization();
			if (children != null && children.size() > 0) {
				result.addAll(getSubOrganizationId(children));
			}
		}
		return result;
	}
}
